﻿using Infragistics.WebUI.UltraWebGrid;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using uMES.LeanManufacturing.ParameterDTO;
using uMES.LeanManufacturing.ReportBusiness;

public partial class Custom_BwCheckManage_BwContainerCheckPopupForm : BaseForm
{
    uMESContainerBusiness containerBal = new uMESContainerBusiness();
    uMESContainerCheckBusiness containerCheckBal = new uMESContainerCheckBusiness();
    uMESWorkReportBusiness report = new uMESWorkReportBusiness();
    uMESCommonBusiness common = new uMESCommonBusiness();

    string businessName = "检验管理", parentName = "conventioncheckinfo";

    protected void Page_Load(object sender, EventArgs e)
    {
        lStatusMessage.Text = "";

        if (IsPostBack == false)
        {
            Session["ConventionCheckConfirm"] = null;

            DataTable dt = PopupData as DataTable;
            Session.Remove("PopupData");
            
            gdContainer.DataSource = dt;
            gdContainer.DataBind();

            InitControl(dt);
        }
    }

    protected void btnAll_Click(object sender, EventArgs e)
    {
        uMESCommonFunction.ResetGridCheckStatus(gdChildContainer, "ckSelect", 0);
    }

    protected void btnNotAll_Click(object sender, EventArgs e)
    {
        uMESCommonFunction.ResetGridCheckStatus(gdChildContainer, "ckSelect", 2);
    }

    protected void CloseButton_Click(object sender, EventArgs e)
    {
        if (btnSubmit.Enabled == false)
        {
            Dictionary<string, string> returnToMain = new Dictionary<string, string>();

            returnToMain["Page"] = "BwContainerCheckPopupForm.aspx";
            returnToMain["Message"] = "检验成功";

            PopupData = returnToMain;
        }
        ClosePopupPage(true);

    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {

        try
        {
            ResultModel re= SaveData();

            DisplayMessage(lStatusMessage, re.Message, re.IsSuccess);

            //不合格数量
            string strNonsenseQty = "0";
            if (!string.IsNullOrEmpty(txtLossQty.Text))
            {
                strNonsenseQty = txtLossQty.Text;
            }

            //如果不合格数量不为0，则不关闭弹出界面
            if (re.IsSuccess)
            {
                btnSubmit.Enabled = false;
                if (strNonsenseQty == "0")
                {
                    Dictionary<string, string> returnToMain = new Dictionary<string, string>();

                    returnToMain["Page"] = "BwContainerCheckPopupForm.aspx";
                    returnToMain["Message"] = "检验成功";

                    PopupData = returnToMain;
                    CloseButton_Click(null, null);
                }
                else
                {
                    btnQR.Enabled = true;
                    DisplayMessage(lStatusMessage, "检验成功，但存在不合格数请进行质量记录填写", true); 
                }

                #region 记录日志
                var ml = new MESAuditLog();
                ml.ContainerName = gdContainer.Rows[0].Cells.FromKey("ContainerName").Text;  ml.ContainerID = gdContainer.Rows[0].Cells.FromKey("ContainerID").Text;
                ml.ParentID = re.Data.ToString(); ml.ParentName = parentName;
                ml.CreateEmployeeID = UserInfo["EmployeeID"];
                ml.BusinessName = businessName; ml.OperationType = 0;
                ml.Description = "批次检验:" + gdContainer.Rows[0].Cells.FromKey("SpecName").Text + ",合格数:" + txtPassQty.Text+",不合格数:"+txtLossQty.Text;
                common.SaveMESAuditLog(ml);
                #endregion
            }


        }
        catch (Exception ex) {
            DisplayMessage(lStatusMessage, ex.Message, false);
        }
    }

    /// <summary>
    /// 初始化控件值
    /// </summary>
    void InitControl(DataTable popDt) {
        //获取子批次号
        DataTable childDt = containerBal.GetTableInfo("reportproductnoinfo", "reportinfoid", popDt.Rows[0]["workreportinfoid"].ToString());
        gdChildContainer.DataSource = childDt;
        gdChildContainer.DataBind();
    }

    /// <summary>
    /// 保存数据
    /// </summary>
    ResultModel SaveData() {
        ResultModel result = new ResultModel(false, "");
        Dictionary<string, object> para = new Dictionary<string, object>();
        para["CheckEmployeeID"] = UserInfo["EmployeeID"];
        para["Notes"] = txtNotes.Text;
        para["ConventionCheckInfoID"] = Guid.NewGuid().ToString();
        para["ConventionCheckInfoName"] = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        para["ContainerID"] = gdContainer.Rows[0].Cells.FromKey("ContainerID").Text;
        para["SpecID"]= gdContainer.Rows[0].Cells.FromKey("SpecID").Text;
        para["ReportInfoID"]= gdContainer.Rows[0].Cells.FromKey("WorkReportInfoID").Text;
        para["CheckType"] = gdContainer.Rows[0].Cells.FromKey("ReportType").Text;

        var qty = int.Parse(gdContainer.Rows[0].Cells.FromKey("Qty").Text);
        if (gdChildContainer.Rows.Count > 0)//有子序号
        {
            DataTable dt1;
            DataTable dt= GetGridChooseInfo(gdChildContainer, out dt1, null, "ckSelect");
            if (dt.Rows.Count == 0)
            {
                if (ConventionCheckConfirm.Text != "0")
                {
                    ConventionCheckConfirm.Text = "0";
                }
                else
                {
                    ConventionCheckConfirm.Text = "1";
                    result.Message = "未勾选合格的子批次，请确认是否全部为不合格，确认后请再次点击“确定”按钮";
                    return result;
                }
            }

            para["ChildContainer"] = dt;
            para["EligibilityQty"] = dt.Rows.Count;
            para["NonsenseQty"] = qty - dt.Rows.Count;
            para["NonNo"] = dt1;
            
        }
        else {//无子序号
            if (string.IsNullOrWhiteSpace(txtPassQty.Text))
            {
                result.Message = "请填入合格数";
                return result;
            }
            
            int passQty = int.Parse(txtPassQty.Text);
            int lossQty = 0;
            if (!string.IsNullOrWhiteSpace(txtLossQty.Text))
            {
                lossQty = int.Parse(txtLossQty.Text);
            }
            if (qty != passQty + lossQty)
            {
                result.Message = "合格数和不合格数之和不等于报工数";
                return result;
            }
            para["EligibilityQty"] = passQty;
            para["NonsenseQty"] = lossQty;

        }

        para["WorkflowID"] = gdContainer.Rows[0].Cells.FromKey("WorkflowID").Text;

        result.IsSuccess = containerCheckBal.SaveCheckData(para);

        //修改报工记录的IsChecked属性
        string strReportID = gdContainer.Rows[0].Cells.FromKey("WorkReportInfoID").Text;

        report.UpdateReportIsChecked(strReportID, 1);
        result.Data = para["ConventionCheckInfoID"];//记录日志所用
        return result;
    }


    /// <summary>
    /// 获取grid选择的行
    /// </summary>
    /// <param name="wg"></param>
    /// <param name="dtNonNo">不合格产品序号列表</param>
    /// <param name="indexList"></param>
    /// <param name="selectKey"></param>
    /// <returns></returns>
    public static DataTable GetGridChooseInfo(UltraWebGrid wg, out DataTable dtNonNo, List<int> indexList, string selectKey)
    {
        DataTable dt = new DataTable();
        DataTable dt1 = new DataTable();

        foreach (UltraGridColumn col in wg.Columns)
        {
            if (dt.Columns.Contains(col.Key))
                continue;
            dt.Columns.Add(col.Key);
            dt1.Columns.Add(col.Key);
        }

        DataRow dr;
        DataRow dr1;

        foreach (UltraGridRow row in wg.Rows)
        {
            UltraGridCell ckSelect = row.Cells.FromKey(selectKey);

            if (ckSelect.Text == "False")
            {
                dr1 = dt1.NewRow();

                foreach (UltraGridColumn col in wg.Columns)
                {
                    dr1[col.Key] = row.Cells.FromKey(col.Key).Value;
                }
                dt1.Rows.Add(dr1);

                continue;
            }

            if (indexList != null)
                indexList.Add(row.Index);//记录选择的索引

            dr = dt.NewRow();

            foreach (UltraGridColumn col in wg.Columns)
            {
                dr[col.Key] = row.Cells.FromKey(col.Key).Value;
            }
            dt.Rows.Add(dr);
        }

        dtNonNo = dt1.Copy();
        return dt;
    }

    protected void btnQR_Click(object sender, EventArgs e)
    {
        try
        {
            Session["PopupData"] = null;

            Dictionary<string, string> popupData = new Dictionary<string, string>();
            //不合格数量
            string strNonsenseQty = "0";
            if (!string.IsNullOrEmpty(txtLossQty.Text))
            {
                strNonsenseQty = txtLossQty.Text;
            }
            popupData.Add("NonsenseQty", strNonsenseQty);
            if (strNonsenseQty == "0")
            {
                DisplayMessage(lStatusMessage, "没有不合格数量，无法进行质量记录填写!", false);
                //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>alert('请选择批次记录')</script>");
                return;
            }

            //工作令号
            string strProcessNo = string.Empty;
            if (!string.IsNullOrEmpty(gdContainer.Rows[0].Cells.FromKey("ProcessNo").Text))
            {
                strProcessNo = gdContainer.Rows[0].Cells.FromKey("ProcessNo").Text;
            }
            popupData.Add("ProcessNo", strProcessNo);

            //作业令号
            string strOprNo = string.Empty;
            if (!string.IsNullOrEmpty(gdContainer.Rows[0].Cells.FromKey("OprNo").Text))
            {
                strOprNo = gdContainer.Rows[0].Cells.FromKey("OprNo").Text;
            }
            popupData.Add("OprNo", strOprNo);

            //批次号
            string strContainerName = string.Empty;
            if (!string.IsNullOrEmpty(gdContainer.Rows[0].Cells.FromKey("ContainerName").Text))
            {
                strContainerName = gdContainer.Rows[0].Cells.FromKey("ContainerName").Text;
            }
            popupData.Add("ContainerName", strContainerName);

            //图号
            string strProductName = string.Empty;
            if (!string.IsNullOrEmpty(gdContainer.Rows[0].Cells.FromKey("ProductName").Text))
            {
                strProductName = gdContainer.Rows[0].Cells.FromKey("ProductName").Text;
            }
            popupData.Add("ProductName", strProductName);

            //名称
            string strProductDesc = string.Empty;
            if (!string.IsNullOrEmpty(gdContainer.Rows[0].Cells.FromKey("ProductDesc").Text))
            {
                strProductDesc = gdContainer.Rows[0].Cells.FromKey("ProductDesc").Text;
            }
            popupData.Add("Description", strProductDesc);

            //批次数量
            string strConQty = string.Empty;
            if (!string.IsNullOrEmpty(gdContainer.Rows[0].Cells.FromKey("ConQty").Text))
            {
                strConQty = gdContainer.Rows[0].Cells.FromKey("ConQty").Text;
            }
            popupData.Add("ConQty", strConQty);

            //计划开始时间
            string strPlannedStartDate = string.Empty;
            if (!string.IsNullOrEmpty(gdContainer.Rows[0].Cells.FromKey("PlannedStartDate").Text))
            {
                strPlannedStartDate =Convert.ToDateTime(gdContainer.Rows[0].Cells.FromKey("PlannedStartDate").Text).ToString("yyyy-MM-dd");
            }
            popupData.Add("StartTime", strPlannedStartDate);

            //计划结束时间
            string strPlannedCompletionDate = string.Empty;
            if (!string.IsNullOrEmpty(gdContainer.Rows[0].Cells.FromKey("PlannedCompletionDate").Text))
            {
                strPlannedCompletionDate =Convert.ToDateTime(gdContainer.Rows[0].Cells.FromKey("PlannedCompletionDate").Text).ToString("yyyy-MM-dd");
            }
            popupData.Add("EndTime", strPlannedCompletionDate);

            //工序
            string strSpecNameDisp = string.Empty;
            if (!string.IsNullOrEmpty(gdContainer.Rows[0].Cells.FromKey("SpecNameDisp").Text))
            {
                strSpecNameDisp = gdContainer.Rows[0].Cells.FromKey("SpecNameDisp").Text;
            }
            popupData.Add("SpecDisName", strSpecNameDisp);

            //跟踪卡ID
            string strContainerID = string.Empty;
            if (!string.IsNullOrEmpty(gdContainer.Rows[0].Cells.FromKey("ContainerID").Text))
            {
                strContainerID = gdContainer.Rows[0].Cells.FromKey("ContainerID").Text;
            }
            popupData.Add("ContainerID", strContainerID);

            //工艺规程ID
            string strWorkflowID = string.Empty;
            if (!string.IsNullOrEmpty(gdContainer.Rows[0].Cells.FromKey("WorkflowID").Text))
            {
                strWorkflowID = gdContainer.Rows[0].Cells.FromKey("WorkflowID").Text;
            }
            popupData.Add("WorkflowID", strWorkflowID);

            //报工单ID
            string strWorkreportInfoID = string.Empty;
            if (!string.IsNullOrEmpty(gdContainer.Rows[0].Cells.FromKey("workreportinfoid").Text))
            {
                strWorkreportInfoID = gdContainer.Rows[0].Cells.FromKey("workreportinfoid").Text;
            }
            popupData.Add("ReportInfoID", strWorkreportInfoID);

            //工序ID
            string strSpecID = string.Empty;
            if (!string.IsNullOrEmpty(gdContainer.Rows[0].Cells.FromKey("SpecID").Text))
            {
                strSpecID = gdContainer.Rows[0].Cells.FromKey("SpecID").Text;
            }
            popupData.Add("SpecID", strSpecID);

            //计量单位ID
            string strUomID = string.Empty;
            if (!string.IsNullOrEmpty(gdContainer.Rows[0].Cells.FromKey("uomid").Text))
            {
                strUomID = gdContainer.Rows[0].Cells.FromKey("uomid").Text;
            }
            popupData.Add("UomID", strUomID);

            //含图号的工序名称 
            string strSpecName = string.Empty;
            if (!string.IsNullOrEmpty(gdContainer.Rows[0].Cells.FromKey("SpecName").Text))
            {
                strSpecName = gdContainer.Rows[0].Cells.FromKey("SpecName").Text;
            }
            popupData.Add("SpecName", strSpecName);



            //报工数量
            string strReportQty = string.Empty;
            if (!string.IsNullOrEmpty(gdContainer.Rows[0].Cells.FromKey("qty").Text))
            {
                strReportQty = gdContainer.Rows[0].Cells.FromKey("qty").Text;
            }
            popupData.Add("ReportQty", strReportQty);

            Session["PopupData"] = popupData;

            var page = "../../uMESQualityRecordInfoPopupForm.aspx";
            var script = String.Format("<script>OpenPopupWindow(false,'{0}','dialogWidth={1}px;dialogHeight={2}px;status=0');</script>", page, 980, 660);

            ClientScript.RegisterStartupScript(this.GetType(), btnQR.Text, script);
        }
        catch (Exception ex)
        {
            //ShowStatusMessage(ex.Message, false);
        }
    }
}